import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui'
import store from '@/store'

Vue.use(VueRouter)

import Home from '@/views/Home'
import Search from '@/views/Search'
import Detail from '@/views/Detail'
import Login from '@/views/Login'
import Register from '@/views/Register'
import AddCartSuccess from '@/views/AddCartSuccess'
import Center from '@/views/Center'
import Pay from '@/views/Pay'
import Trade from '@/views/Trade'
import PaySuccess from '@/views/PaySuccess'
import ShopCart from '@/views/ShopCart'
const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/home',
      component: Home,
    },
    {
      name: 'Search',
      path: '/search',
      component: Search,
    },
    {
      name: 'Detail',
      path: '/detail/:id',
      component: Detail,
    },
    {
      name: 'AddCartSuccess',
      path: '/addCartSuccess',
      component: AddCartSuccess,
    },
    {
      name: 'Shopcart',
      path: '/shopcart',
      component: ShopCart,
    },
    {
      name: 'Center',
      path: '/center',
      component: Center,
    },
    {
      name: 'Pay',
      path: '/pay',
      component: Pay,
    },
    {
      name: 'Trade',
      path: '/trade',
      component: Trade,
    },
    {
      name: 'PaySuccess',
      path: '/paysuccess',
      component: PaySuccess,
    },
    {
      path: '/login',
      component: Login,
      meta: {
        isHiddenFooter: true,
      },
    },
    {
      path: '/register',
      component: Register,
      meta: {
        isHiddenFooter: true,
      },
    },
  ],
  scrollBehavior() {
    return {
      x: 0,
      y: 0,
    }
  },
})

const authList = ['/center', '/pay', '/trade', '/paysuccess']
router.beforeEach((to, from, next) => {
  // if (to.path === '/login') {
  //   next()
  //   return
  // }
  // next('/login')

  // 路径不是权限列表里面路径，就先登录’，
  // 路径是权限列表里面的，要考虑有没有token
  // 有token，就直接跳转，没有token，先登录再继续访问
  // if (authList.includes(to.path)) {
  //   const token = store.state.user.token
  //   if (token) {
  //     next()
  //   } else {
  //     Message.error(' 请先登录，再访问')
  //     next('/login')
  //   }
  // } else {
  //   next()
  // }
  const token = store.state.user.token
  if (token) {
    // 登陆了
    if (to.path === '/login') {
      // 已经登陆过，就没必要再登录了，直接跳转到首页
      next('/')
    } else {
      // 如果登陆过，不是登录界面，可以继续访问
      next()
    }
  } else {
    // 没有登陆,
    if (authList.includes(to.path) && !token) {
      // 没有登录，不能访问authList，要先登录
      Message.error('请先登录，再访问')
      // 将想要访问的参数作为query参数传递给登录组件
      next(`/login?redirect=${to.path}`)
    } else {
      next()
    }
  }
})
export default router
